var Promise = require("node-promise/promise").Promise;

function response(data, cb, err) {
    if (typeof cb == "function") {
        cb(data, err);
    } else {
        var promise = new Promise();

        if (data) {
            promise.resolve(data);
        }

        if (err) {
            promise.reject(err);
        }

        return promise;
    }
}

/**
 * In-memory imlementation is async to avoid API changes if implementing a
 * persistent backend.
 */
module.exports = {
    create: function () {
        return Object.create(this);
    },

    all: function (cb) {
        this.items = this.items || [];
        return response(this.items, cb);
    },

    add: function (text, cb) {
        this.items = this.items || [];

        var item = {
            text: text,
            id: this.items.length,
            done: false
        };

        this.items.push(item);
        return response(item, cb);
    },

    get: function (id, cb) {
        if (this.items && this.items[id]) {
            return response(this.items[id], cb);
        } else {
            return response(null, cb, new Error("No such error"));
        }
    },

    complete: function (id, cb) {
        if (this.items && this.items[id]) {
            this.items[id].done = true;
            return response(this.items[id], cb);
        } else {
            return response(null, cb, new Error("No such item"));
        }
    }
};
